package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Override
    public List<Category> findAll() {
        List<Category> categoryList = categoryMapper.findAll();
        return categoryList;
    }

    @Override
    public void save(Category category) {
        //设置主键
        category.setId(IdUtil.getSnowflake(1,1).nextId());
        //设置操作人操作时间
//        category.setCreateTime(new Date());
//        category.setUpdateTime(new Date());
//        category.setCreateUser(1L);
//        category.setUpdateUser(1L);

        //调用mapper
        categoryMapper.save(category);
    }

    @Override
    public void update(Category category) {
        //设置修改人修改时间
//        category.setUpdateTime(new Date());
//        category.setUpdateUser(1L);
        categoryMapper.updateById(category);
    }

    @Override
    public ResultInfo delete(Long id) {
        //调用mapper查询当前菜品下是否有菜品数量，如果有返回错误
        int count1 = categoryMapper.countDishByCategoryId(id);
        if (count1 > 0) {
            throw new CustomException("当前分类下存在菜品，不能删除");
        }

        //调用mapper查询当前套餐下是否有套餐数量，如果有返回错误
        int count2 = categoryMapper.countSetmealByCategoryId(id);
        if (count2 > 0) {
            throw new CustomException("当前分类下存在套餐，不能删除");
        }

        //根据id删除
        categoryMapper.delete(id);
        return ResultInfo.success(null);
    }

    @Override
    public List<Category> findList(Integer type) {
        //组装条件
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getType, type);

        //执行查询
        return categoryMapper.selectList(wrapper);
    }
}
